<script lang="ts" setup>
  import appStore from '@/store'
  import aliases, { aliasMsg } from '@/api/aliases'
  import MeSearch from '@/components/Search.vue'
  import { reactive, ref, computed } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { timeFormatUTC } from '@/utils/formatter'
  import { ElMessage, ElMessageBox } from 'element-plus'
  const router = useRouter()
  const route = useRoute()
  let seaeAll = {}
  let searchArr: Array<{ [key: string]: string }> = reactive([])
  let comingState = ref({} as { [key: string]: string })
  const param = reactive({
    project_id: appStore.userStore.project_id,
    offset: 1,
    limit: 10,
    fleet_id: '',
    url: '',
    policy_id: '',
    name: '',
    type: ''
  })
  const alias: aliasMsg = reactive({
    project_id: appStore.userStore.project_id,
    alias_id: ''
  })
  const ys = {
    fleet_id: 'fleet id',
    name: '别名名称',
    type: '别名类型'
  }
  let searchData = computed(() => {
    return {
      inputSearch: {
        fleet_id: { name: '别名关联的fleet id' },
        name: { name: '别名名称' }
      },
      choseSearch: {
        type: {
          name: '别名类型',
          num: 0,
          data: [
            { value: 'ACTIVE', text: '激活' },
            { value: 'DEACTIVE', text: '停用' }
          ]
        }
      }
    }
  })
  interface apiData {
    name?: string
    client_session_creating_policy?: string
    created_time?: string
    creator_id?: string
    current_client_session_count?: number
    fleet_id?: string
    instance_id?: string
    ip_address?: string
    max_client_session_num?: number
    port?: number
    process_id?: string
    server_session_id?: string
    server_session_protection_policy?: string
    server_session_protection_time_limit_minutes?: number
    session_data?: string
    session_properties?: Array<object>
    state?: string
    state_reason?: string
    updated_time?: string
    bandwidth?: number
    build_id?: string
    creation_time?: string
    description?: string
    enable_auto_scaling?: boolean
    operating_system?: string
    region?: string
    resource_creation_limit_policy?: object
    scaling_interval_minutes?: number
  }
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  let tableData: apiData[] = reactive([])
  let tableTotal = ref(0)
  const getAliasesList = async () => {
    let res = await aliases.getAliasesList(param, seaeAll)
    tableTotal.value = res.data.total_count
    tableData.length = 0
    tableData.push(...res.data.aliases)
  }
  const setSearchArr = (arr: Array<{ [key: string]: string }>) => {
    searchArr.length = 0
    searchArr.push(...arr)
    let obj: { [key: string]: string } = {}
    searchArr.forEach((item) => {
      let temp_arr = item.value.split(';')
      let value_arr: (string | number)[] = []
      temp_arr.forEach((val) => {
        if (val === '是') {
          value_arr.push(1)
        } else if (val === '否') {
          value_arr.push(0)
        } else {
          value_arr.push(val)
        }
      })
      obj[item.key] = value_arr.join(';')
    })
    seaeAll = obj
    param.offset = 1
    getAliasesList()
  }
  if (route.query.type) {
    if (typeof route.query.type == 'string') {
      comingState.value = { key: 'type', value: route.query.type }
      setSearchArr([comingState.value])
    }
  }
  const buildAlias = () => {
    router.push({
      name: 'createAlias'
    })
  }
  getAliasesList()
  const small = ref(false)
  const disabled = ref(false)
  const background = ref(true)
  const handleSizeChange = (val: number) => {
    param.limit = val
    param.offset = 1
    getAliasesList()
  }
  const handleCurrentChange = (val: number) => {
    param.offset = val
    getAliasesList()
  }

  const showDetails = (id: any) => {
    router.push({
      name: 'aliasDetail',
      params: {
        id
      }
    })
  }
  const deleteAs = (alias_id: string, name: string) => {
    ElMessageBox.confirm(`确认删除此条数据？\n名称: ${name}\nID: ${alias_id} `, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        alias.alias_id = alias_id
        let res = await aliases.deleteAlias(alias)
        if (res.status < 300) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getAliasesList()
        } else {
          ElMessage({
            type: 'info',
            message: '删除失败'
          })
        }
      })
      .catch(() => {})
  }
</script>
<template>
  <div id="aliasManager" class="list-index">
    <div class="run-box">
      <div class="state-box">
        <div class="run-label">别名管理</div>
      </div>
    </div>
    <div class="top-button" v-if="userType >= 5">
      <button class="btn new" @click="buildAlias">新建别名</button>
    </div>
    <div class="table-box">
      <div class="search-box">
        <me-search :search="searchData" :ys="ys" :searchConArr="searchArr" @search="setSearchArr"></me-search>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafe', color: '#1d1d1f' }"
        :border="true"
        :default-sort="{ prop: 'creation_time', order: 'descending' }"
      >
        <el-table-column label="别名/ID" class-name="elcell" width="260">
          <template #default="scope">
            <div class="toDetails" @click="showDetails(scope.row.alias_id)">
              {{ scope.row.name }}
            </div>
            <el-tooltip effect="dark" :content="scope.row.alias_id" placement="bottom">
              <div class="id-box">
                {{ scope.row.alias_id }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="描述">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.description" placement="bottom">
              <div class="idescribe">
                {{ scope.row.description }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="associated_fleets.length" label="关联Fleet数量" />
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            {{ scope.row.type ? $t('alias.' + scope.row.type) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="creation_time" label="创建时间" :formatter="timeFormatUTC" sortable />
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <div class="actions-box">
              <div class="actions-details" @click="showDetails(scope.row.alias_id)">详情</div>
              <div class="line" v-if="userType >= 5"></div>
              <div class="actions-delete" @click="deleteAs(scope.row.alias_id, scope.row.name)" v-if="userType >= 5">删除</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="param.offset"
        v-model:page-size="param.limit"
        :page-sizes="[10, 20, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/list.scss';
  .search-box {
    margin-bottom: 20px;
  }
</style>
